package com.houmeiyuan.huiguniang.ctrl;

import com.houmeiyuan.huiguniang.common.MessageConstVar;
import com.houmeiyuan.huiguniang.common.Result;
import com.houmeiyuan.huiguniang.common.Util;
import com.houmeiyuan.huiguniang.modles.domain.WxUser;
import com.houmeiyuan.huiguniang.service.MessageService;
import com.houmeiyuan.huiguniang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author wzn
 * @date2019-07-20 16:16
 */
@RestController
@RequestMapping("/common")
public class CommonCtrl extends BaseCtrl{
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @PostMapping("/registerByWX")
    public Result getUserInfo(@RequestParam("openId")String openId )
    {
        WxUser u=userService.selectByOpenId(openId);
        Map<String,Object> mp =new LinkedHashMap<>();
        mp.put("openid",u.getOpenId());
        mp.put("wxusername",u.getWxusername());
        mp.put("userphoto",u.getImagePath());
        mp.put("userphone",u.getPhone());
        return send(mp);
    }
  /*  public Result register(@Valid User user){
        Date createTime = new Date();
        user.setCreateTime(createTime);
        return send(userService.registerByWX(user));
    }*/

  @GetMapping("/phoneCode")
    public Result sendSMSCode(HttpServletRequest request,@RequestParam("phone") String phone){
     try {
         if (Util.checkCellphone(phone)) {
             String code = messageService.sendMessageCode(phone);
             System.out.println(code);
             this.setValueToSession("code", code, request);
             return send(MessageConstVar.SuccessCode, MessageConstVar.Success);
         }
         return send(MessageConstVar.AccountFormCode, MessageConstVar.AccountForm);
     }catch (Exception e){
         System.out.println(e.getMessage());
         return send(MessageConstVar.ErrorCode,MessageConstVar.Error);
     }

  }

    /**
     * 验证手机号是否已注册
     *
     * @param phone
     * @return
     * @author nkz
     */
    @GetMapping("/check/phone")
    public Result changePhone(@RequestParam(value = "phone",required = false) String phone){
        try{
            WxUser wxUser = userService.selectByphone(phone);
            return send(wxUser,0,"该号已被注册");
        } catch (Exception e){
            e.printStackTrace();
            return send(1,"该号未被注册,可以注册");
        }
    }

}
